<?php
declare (strict_types = 1);

namespace app\dashboard\controller;

use think\facade\View;
use think\facade\Db;
use app\model\Page;
use think\Request;
use think\exception\ValidateException;

class Pages
{
    public function index(String $keyword="")
    {
        View::assign('keyword', $keyword);

        $query = Db::table('qnz_pages')->where('active',1);      
        if(!empty($keyword)){
            $query = $query->where('title','like','%'.$keyword.'%')->whereOr('content','like','%'.$keyword.'%');
        }
        $total = $query->count();
        $list =  $query->paginate(10);
        $page = $list->render();
        // 模板变量赋值
        View::assign('list', $list);
        View::assign('page', $page);
        View::assign('pageCount', $total);
        // 渲染模板输出
        return View::fetch('pages/index');
    }
  
    public function add(Request $request)
    {       
        $token = $request->buildToken('__token__', 'sha1');
        View::assign('token', $token);
        View::assign('title', '添加');       
        return View::fetch('pages/edit');
    }

  
    public function edit(Request $request, $id)
    {
        $token = $request->buildToken('__token__');
        header('X-CSRF-TOKEN:'.$token);
        View::assign('token', $token);
        
        $data = Db::table('qnz_pages')->find($id);
        View::assign('title', '编辑');       
        View::assign('id', $id);
        View::assign('page', $data);
        return View::fetch('pages/edit');
    }

    public function recommend($id)
    {
        // $token = $request->buildToken('__token__');
        // header('X-CSRF-TOKEN:'.$token);
        // View::assign('token', $token);
        
        //Db::table('qnz_pages')->save(['id' => $id, 'recommend' => 1]);
      
        $data = Db::table('qnz_pages')->find($id);
        $data->recommend = !($data->recommend);
        $data->save();

        return json_encode(array ('status'=>1,'message'=>'更新成功')); 
    }

    public function update(Request $request)
    {
        // $check = $request->checkToken('__token__');
        
        // if(false === $check) {
        //     throw new ValidateException('invalid token');
        // }


        $data = input('post.');
        //print_r(($data));
        $data['active'] = isset($data['active'])?1:0;
        if($data['id']==0){
            Db::table('qnz_pages')->insert($data);
        }else{
            Db::table('qnz_pages')->update($data);         
        }
        
        // View::assign('title', '编辑');       
        // View::assign('id', $id);
        return json_encode(array ('status'=>1,'message'=>'更新成功')); 
    }
}
